package com.weaver.qfengx.action;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.NumberUtils;
import com.weaver.qfengx.RegexUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.annotation.ActionParamCheck;
import weaver.soa.workflow.request.RequestInfo;

import java.util.List;
import java.util.Map;

public class WorkflowNumberAction extends BaseAction {

    public WorkflowNumberAction() {
        setActionName("自定义字段流程编号生成");
    }

    // 流水号位数
    @ActionParamCheck(errorMsg = "流水号位数未配置")
    private String number;
    // 流水号匹配表达式
//    ${field.showval}-$code$ // code为流水号
    @ActionParamCheck(errorMsg = "匹配表达式未配置")
    private String regex;
    // 编号回写字段
    @ActionParamCheck(errorMsg = "编号回写字段未配置")
    private String field;
    // 序号表
    @ActionParamCheck(errorMsg = "编号表名未配置")
    private String numbertable;

    private String checkTable;
    private String checkTableField;

    @Override
    public void execCode(RequestInfo requestInfo) throws Exception {
        synchronized (WorkflowNumberAction.class) {
            StringBuilder regval = new StringBuilder(regex);
            RegexUtils.regHangle("\\$\\{([a-zA-Z0-9.]+)\\}", regex, (m, str) -> {
                List<String> fields = Splitter.on(".").trimResults().omitEmptyStrings().splitToList(m.group(1));
                String fieldsVal = fields.get(0);
                boolean isShowval = true;
                if (fields.size() == 2) {
                    fieldsVal = fields.get(0);
                    if (!StringUtils.equalsIgnoreCase("showval", fields.get(1))) {
                        isShowval = false;
                    }
                }
                String replStr = "\\$\\{%s\\}";
                String tempRegVal = regval.toString();
                regval.delete(0, tempRegVal.length());
                regval.append(tempRegVal.replaceAll(String.format(replStr, m.group(1)), mainTableMap.getOrDefault(fieldsVal, "")));
            });


            // 查询数据库当前的序号
            Map<String, String> map = DaoUtils.executeQueryToMap(String.format("select id, xhwb, dqxh from %s where xhwb = ?", numbertable), regval.toString());
            int dqxh = map == null ? 1 : NumberUtils.parseInt(map.getOrDefault("dqxh", "0"), 1);
            // 流程编号已存在
            if (StringUtils.isNotEmpty(mainTableMap.getOrDefault(field, ""))
                    && (map != null && StringUtils.equals(map.getOrDefault("xhwb", ""), regval.toString()))) {

                // 流程编号已存在则 判断台账是否存在
                if (StringUtils.isNotEmpty(checkTable) && StringUtils.isNotEmpty(checkTableField)) {
                    int c = NumberUtils.parseInt(DaoUtils.querySingleVal(String.format("select count(1) from %s where %s = ?", checkTable, checkTableField), mainTableMap.getOrDefault(field, "")), 0);
                    if (c > 0) {
                        isOk = false;
                        message = "台账中编号已存在，请重新生成编号";
                        return;
                    }
                }
                return;
            }
            int num = NumberUtils.parseInt(number, 1);
            int d = (int) Math.pow(10, num);
            String wfcode = "";
            int has = 0;
            do {
                if (has != 0) dqxh++;
                if (dqxh > d) {
                    dqxh %= d;
                }
                wfcode = regval.toString().replaceAll("\\$code\\$", String.format("%0" + num + "d", dqxh));
                if (StringUtils.isNotEmpty(checkTable) && StringUtils.isNotEmpty(checkTableField)) {
                    has = NumberUtils.parseInt(DaoUtils.querySingleVal(String.format("select count(1) from %s where %s = ?", checkTable, checkTableField), wfcode), 0);
                }
            } while (has != 0);
            if (map == null) { // 插入数据
                DaoUtils.insert(numbertable, Lists.newArrayList("xhwb", "dqxh"), Lists.newArrayList(regval.toString(), dqxh + 1));
            } else {
                DaoUtils.executeUpdate(String.format("update %s set dqxh = ? where id = ?", numbertable), dqxh + 1, map.get("id"));
            }
            // 回写到表单中

            DaoUtils.executeUpdate(String.format("update %s set %s = ? where requestid = ?", maintable, field), wfcode, requestid);
        }
    }

    public static void main(String[] args) {
        String reg = "${ceshi.showval}-$code$";
        StringBuilder regval = new StringBuilder(reg);
        RegexUtils.regHangle("\\$\\{([a-zA-Z0-9.]+)\\}", reg, (m, str) -> {
            List<String> fields = Splitter.on(".").trimResults().omitEmptyStrings().splitToList(m.group(1));
            String fieldsVal = fields.get(0);
            boolean isShowval = true;
            if (fields.size() == 2) {
                fieldsVal = fields.get(0);
                if (!StringUtils.equalsIgnoreCase("showval", fields.get(1))) {
                    isShowval = false;
                }
            }
            String replStr = "\\$\\{%s\\}";
            String strs = regval.toString();
            regval.delete(0, regval.length());
            regval.append(strs.replaceAll(String.format(replStr, m.group(1)), "1"));
            System.out.println(fieldsVal + "-" + isShowval);
        });


        System.out.println(regval.toString());
        int s = 121;
        int num = 1;
        int d = (int) Math.pow(10, num);
        if (s > d) {
            s %= d;
        }
        System.out.println(String.format("%0" + num + "d", s));
        System.out.println(121 % 100);
    }
}

